package me.zhengjie.modules.thumbnail.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import lombok.AllArgsConstructor;
import me.zhengjie.base.PageInfo;
import me.zhengjie.base.QueryHelpMybatisPlus;
import me.zhengjie.base.impl.CommonServiceImpl;
import me.zhengjie.config.FileProperties;
import me.zhengjie.exception.BadRequestException;
import me.zhengjie.modules.banner.domain.Banner;
import me.zhengjie.modules.company.service.mapper.CompanyMapper;
import me.zhengjie.modules.dcompany.domain.DependentCompany;
import me.zhengjie.modules.dcompany.service.mapper.DependentCompanyMapper;
import me.zhengjie.modules.detail.domain.RealEstateProjectDetail;
import me.zhengjie.modules.detail.service.mapper.RealEstateProjectDetailMapper;
import me.zhengjie.modules.realestate.domain.RealEstateProject;
import me.zhengjie.modules.realestate.service.mapper.RealEstateProjectMapper;
import me.zhengjie.modules.thumbnail.domain.vo.ThumbnailVo;
import me.zhengjie.utils.ConvertUtil;
import me.zhengjie.utils.FileUtil;
import me.zhengjie.utils.PageUtil;
import me.zhengjie.modules.thumbnail.domain.Thumbnail;
import me.zhengjie.modules.thumbnail.service.ThumbnailService;
import me.zhengjie.modules.thumbnail.service.dto.ThumbnailDto;
import me.zhengjie.modules.thumbnail.service.dto.ThumbnailQueryParam;
import me.zhengjie.modules.thumbnail.service.mapper.ThumbnailMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
// 默认不使用缓存
//import org.springframework.cache.annotation.CacheConfig;
//import org.springframework.cache.annotation.CacheEvict;
//import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Pageable;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.*;

/**
 * @author TianI
 * @date 2022-02-14
 */
@Service
@AllArgsConstructor
// @CacheConfig(cacheNames = ThumbnailService.CACHE_KEY)
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class ThumbnailServiceImpl extends CommonServiceImpl<ThumbnailMapper, Thumbnail> implements ThumbnailService {
    private final FileProperties properties;

    // private final RedisUtils redisUtils;
    private final ThumbnailMapper thumbnailMapper;
    private final CompanyMapper companyMapper;
    private final DependentCompanyMapper dCompanyMapper;
    private final RealEstateProjectDetailMapper detailMapper;
    private final RealEstateProjectMapper realEstateMapper;

    @Override
    public PageInfo<ThumbnailDto> queryAll(ThumbnailQueryParam query, Pageable pageable) {
        IPage<Thumbnail> queryPage = PageUtil.toMybatisPage(pageable);
        IPage<Thumbnail> page = thumbnailMapper.selectPage(queryPage, QueryHelpMybatisPlus.getPredicate(query));
        return ConvertUtil.convertPage(page, ThumbnailDto.class);
    }

    @Override
    public List<ThumbnailDto> queryAll(ThumbnailQueryParam query) {
        return ConvertUtil.convertList(thumbnailMapper.selectList(QueryHelpMybatisPlus.getPredicate(query)), ThumbnailDto.class);
    }

    @Override
    public Thumbnail getById(Long id) {
        return thumbnailMapper.selectById(id);
    }

    @Override
    // @Cacheable(key = "'id:' + #p0")
    public ThumbnailDto findById(Long id) {
        return ConvertUtil.convert(getById(id), ThumbnailDto.class);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insert(ThumbnailDto resources) {
        Thumbnail entity = ConvertUtil.convert(resources, Thumbnail.class);
        return thumbnailMapper.insert(entity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateById(ThumbnailDto resources) {
        Thumbnail entity = ConvertUtil.convert(resources, Thumbnail.class);
        int ret = thumbnailMapper.updateById(entity);
        // delCaches(resources.id);
        return ret;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int removeByIds(Set<Long> ids) {
        // delCaches(ids);
        return thumbnailMapper.deleteBatchIds(ids);
    }

    @Override
    public Thumbnail create(MultipartFile multipartFile) {
        FileUtil.checkSize(properties.getMaxSize(), multipartFile.getSize());
        String suffix = FileUtil.getExtensionName(multipartFile.getOriginalFilename());
        String type = FileUtil.getFileType(suffix);
        File file = FileUtil.upload(multipartFile, properties.getPath().getPath() + type + File.separator);
        if (ObjectUtil.isNull(file)) {
            throw new BadRequestException("上传失败");
        }
        try {
            Thumbnail thumbnail = new Thumbnail();
            thumbnail.setThumbnailUrl(file.getName());
            thumbnailMapper.insert(thumbnail);
            return thumbnail;
        } catch (Exception e) {
            FileUtil.del(file);
            throw e;
        }
    }

    @Override
    public List<ThumbnailVo> queryThumbnail(Long id) {
        List<DependentCompany> dCompany = dCompanyMapper.selectList(new QueryWrapper<DependentCompany>().eq("company_id", id));
        List<ThumbnailVo> thumbnailVoList  =new ArrayList<ThumbnailVo>();
        for (DependentCompany dependentCompany : dCompany) {
            List<RealEstateProject> realEstateProjects = realEstateMapper.selectList(new QueryWrapper<RealEstateProject>().eq("dcompany_id", dependentCompany.getDcompanyId()));
            for (RealEstateProject realEstateProject : realEstateProjects) {
                Long realEstateProjectDetailId = realEstateProject.getRealEstateProjectDetailId();
                ThumbnailVo vo = new ThumbnailVo();
                vo.setRealestateId(realEstateProjectDetailId);
                Thumbnail thumbnail = thumbnailMapper.selectOne(new QueryWrapper<Thumbnail>().eq("real_estate_project_id", realEstateProjectDetailId));
                vo.setThumbnailUrl(thumbnail.getThumbnailUrl());
                thumbnailVoList.add(vo);
            }
        }
        return thumbnailVoList;
    }

    @Override
    public List<ThumbnailVo> getByName(String name) {
        List<RealEstateProjectDetail> real_estate_project_name = detailMapper.selectList(new QueryWrapper<RealEstateProjectDetail>().like("real_estate_project_name", name));
        List<ThumbnailVo> thumbnailVoList  =new ArrayList<ThumbnailVo>();
        for (RealEstateProjectDetail detail : real_estate_project_name) {
            Long realEstateProjectDetailId = detail.getRealEstateProjectDetailId();
            ThumbnailVo vo = new ThumbnailVo();
            vo.setRealestateId(realEstateProjectDetailId);
            Thumbnail thumbnail = thumbnailMapper.selectOne(new QueryWrapper<Thumbnail>().eq("real_estate_project_id", realEstateProjectDetailId));
            vo.setThumbnailUrl(thumbnail.getThumbnailUrl());
            thumbnailVoList.add(vo);
        }
        return thumbnailVoList;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int removeById(Long id) {
        Set<Long> set = new HashSet<>(1);
        set.add(id);
        return this.removeByIds(set);
    }

    /*
    private void delCaches(Long id) {
        redisUtils.delByKey(CACHE_KEY + "::id:", id);
    }

    private void delCaches(Set<Long> ids) {
        for (Long id: ids) {
            delCaches(id);
        }
    }*/

    /*
    @Override
    public void download(List<ThumbnailDto> all, HttpServletResponse response) throws IOException {
      List<Map<String, Object>> list = new ArrayList<>();
      for (ThumbnailDto thumbnail : all) {
        Map<String,Object> map = new LinkedHashMap<>();
              map.put("关联房产项目id", thumbnail.getRealEstateProjectId());
              map.put("缩略图地址", thumbnail.getThumbnailUrl());
              map.put("创建时间", thumbnail.getCreateTime());
              map.put("修改时间", thumbnail.getUpdateTime());
        list.add(map);
      }
      FileUtil.downloadExcel(list, response);
    }*/
}
